
package de.uni.wuppertal.server.ui.support;

import java.awt.EventQueue;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;

import javax.swing.AbstractListModel;

import de.uni.wuppertal.server.ServerInfo;

/**
 * @author Martin Schröder
 * @author Patrik Nordsiek
 */
public class ServerListModel extends AbstractListModel
{
	private static final long serialVersionUID = 1L;
	
	private List<ServerInfo> servers = new ArrayList<ServerInfo>();
	
	public synchronized void addServer(ServerInfo server)
	{
		servers.add(server);
		
		Collections.sort(servers);
		
		updateListeners();
	}
	
	public synchronized void removeServer(ServerInfo server)
	{
		Iterator<ServerInfo> it = servers.iterator();
		
		while(it.hasNext())
		{
			ServerInfo current = it.next();
			
			if(current == server)
			{
				it.remove();
				
				updateListeners();
				
				break;
			}
		}
	}
	
	public synchronized void removeAllServers()
	{
		servers.clear();
		
		updateListeners();
	}
	
	@Override
	public Object getElementAt(int index)
	{
		try
		{
			return servers.get(index);
		}
		catch(Throwable e)
		{
			return null;
		}
	}
	
	@Override
	public int getSize()
	{
		return servers.size();
	}
	
	private void updateListeners()
	{
		EventQueue.invokeLater(new Runnable()
		{
			@Override
			public void run()
			{
				fireContentsChanged(ServerListModel.this, 0, servers.size() - 1);
			}
		});
	}
}
